﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using ZhuXingFamilys.MainViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Category = ZhuXingFamilys.MainViewModel.Category;
using ZhuXingFamilys.Help;
using System.Runtime.InteropServices;
using MaterialDesignThemes.Wpf;
using MaterialDesignColors;
using ZhuXingFamilys.utils;
using Visibility = System.Windows.Visibility;
using System.Windows.Threading;
using ComboBox = Autodesk.Revit.UI.ComboBox;

namespace ZhuXingFamilys.MainFamilyView
{
    /// <summary>
    /// MainFamilyView.xaml 的交互逻辑
    /// </summary>
    public partial class MainFamilyView : Window
    {
        private static MainFamilyView staticInstance = null;
        public MainFamilyView(string SelectValue)
        {
            //ui库使用
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));

            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            InitializeComponent();

            selectvalue = SelectValue;
            this.InputData();

            loadFamily = new LoadFamily();
            LoadFamilyEvent = ExternalEvent.Create(loadFamily);

            this.Closed += WindowOnClosed;

        }

        private void WindowOnClosed(object sender, System.EventArgs e)
        {
            staticInstance = null;
        }

        public static MainFamilyView GetInstance()
        {
            if (staticInstance == null)
            {
                staticInstance = new MainFamilyView("");
            }

            return staticInstance;
        }
        // 窗口加载完成
        private void MainFamilyView_OnLoaded(object sender, RoutedEventArgs e)
        {
            //getParameters();
        }

        public static string FileAddress;
        //第一个启动加载数据
        private void InputData()
        {
            try
            {
                FamilyData();
                TreeNodeData();
                CategoryData();
                getParameters();
            }
            catch (Exception e)
            {
                MessageBox.Show("数据库连接失败,请检查网络", "提示");
                throw;
            }
            FileAddress = Set.settingaddress("Setup.ini");
            chapterTree.ItemsSource = GetNodes(0, TreeNodes, "建筑");
            listBox.ItemsSource = ListBoxFamily(pagesize, "1", selectvalue);
            CategoryModes.ItemsSource = Categorys;
        }
        //加载树
        private List<TreeNode> GetNodes(int parentID, List<TreeNode> TreeNodes, string NodeCategory)
        {
            List<TreeNode> mainNodes = TreeNodes.Where(x => x.ParentID == parentID).Where(x => x.NodeCategory == NodeCategory).ToList();
            List<TreeNode> otherNodes = TreeNodes.Where(x => x.ParentID != parentID).ToList();
            foreach (TreeNode node in mainNodes)
                node.ChildNodes = GetNodes(node.NodeID, otherNodes, NodeCategory);
            return mainNodes;
        }



        #region  翻页函数
        //首页
        private void btnFirst_Click(object sender, RoutedEventArgs e)
        {
            tbindex.Text = 1.ToString();
            tbindexnum = 1;
            index = 0;
            listBox.ItemsSource = ListListBoxItem.Skip(0).Take(pagesize).ToList();
        }

        //尾页
        private void btnLast_Click(object sender, RoutedEventArgs e)
        {
            tbindex.Text = tbmaxnum.ToString();
            tbindexnum = tbmaxnum;
            index = (tbmaxnum - 1) * pagesize;
            listBox.ItemsSource = ListListBoxItem.Skip(index).Take(pagesize).ToList();
        }

        //上一页
        private void btnPrev_Click(object sender, RoutedEventArgs e)
        {
            if (tbindexnum > 1)
            {
                tbindex.Text = (--tbindexnum).ToString();
                index -= 16;
                listBox.ItemsSource = ListListBoxItem.Skip(index).Take(pagesize).ToList();
            }
            else
            {
                MessageBox.Show("已经到最前了");
            }
        }

        //下一页
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (tbindexnum < tbmaxnum)
            {
                tbindex.Text = (++tbindexnum).ToString();
                index += 16;
                listBox.ItemsSource = ListListBoxItem.Skip(index).Take(pagesize).ToList();
            }
            else
            {
                MessageBox.Show("已经到最后了");
            }
        }
        #endregion

        public ObservableCollection<FamilyFile> FamilyFiles { get; set; }
        public ObservableCollection<Category> Category { get; set; }

        public string selectvalue = "";
        LoadFamily loadFamily = null;
        ExternalEvent LoadFamilyEvent = null;
        List<ListBoxItem> ListListBoxItem;
        int index = 0;
        int pagesize = 36;
        int tbindexnum = 1;
        int tbmaxnum;
        //族文件展示
        public List<ListBoxItem> ListBoxFamily(int pagesize, string NodeID = "", string SelectText = "")
        {
            ListListBoxItem = new List<ListBoxItem>();
            int listLength = 0;
            List<FamilyFile> Familyss = null;
            if (SelectText.Length == 0 && NodeID.Length != 0)
            {
                Familyss = FamilyFiles.Where(x => x.FamilyNodeID.Replace(" ", "") == NodeID).ToList();
            }
            else
            {
                Familyss = FamilyFiles.Where(x => x.FamilyName.Contains(SelectText)).ToList();

            }
            listLength = Familyss.Count;
            for (int i = 0; i < listLength; i++)
            {
                //DispatherHelper.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() =>
                //{
                //    DetailImages.Add(image);
                //}));

                //CheckBox checkBox = new CheckBox();
                //checkBox.Width = 100;
                //checkBox.Name = "dfas";
                ListBoxItem lbi = new ListBoxItem();
                //lbi.ToolTip = Familyss[i].ProjectFeatures;
                lbi.Height = 160;
                lbi.Width = 160;
                lbi.Margin = new Thickness(5);
                lbi.HorizontalContentAlignment = HorizontalAlignment.Center;
                lbi.HorizontalAlignment = HorizontalAlignment.Center;
                StackPanel sp = new StackPanel();
                sp.HorizontalAlignment = HorizontalAlignment.Center;
                Image image = new Image();
                image.Height = 60;
                image.Height = 60;
                image.ToolTip = Familyss[i].FamilyName;
                try
                {
                    var img = new BitmapImage();
                    img.BeginInit();
                    string Path = FileAddress;
                    string ImageFullPath = Path + "\\" + Familyss[i].FamilyNodeID + "\\" + Familyss[i].FamilyName + ".png";
                    img.StreamSource = new MemoryStream(File.ReadAllBytes(ImageFullPath));
                    img.EndInit();
                    image.Source = img;
                }
                catch (Exception)
                {
                    image.Source = CsAddpanel.convertFromBitmap(Properties.Resource.公共族库);
                }
                Label label = new Label
                {
                    Name = "familyName",
                    Width = 120
                };
                //label.ToolTip = Familyss[i].FamilyName;
                label.Content = Familyss[i].FamilyName;
                label.HorizontalContentAlignment = HorizontalAlignment.Center;

                Label lable1 = new Label
                {
                    Name = "author",
                    Content = Familyss[i].author
                };
                lable1.HorizontalAlignment = HorizontalAlignment.Center;

                // 传参使用 无意义
                Label lable2 = new Label
                {
                    Name = "configurable",
                    Visibility = Visibility.Collapsed,
                    Content = Familyss[i].Configurable
                };

                string FamilyFileCategory = Familyss[i].FamilyFileCategory;
                string FamilyCategoryName = Familyss[i].FamilyCategoryName;
                string FamilyNodeID = Familyss[i].FamilyNodeID;
                string FamilyID = Familyss[i].FamilyID;



                //string TemplateUri = "pack://application:,,,/Settings.xaml";
                //string TemplateUri = "..\\..\\Settings.xaml";
                //ResourceDictionary dic = new ResourceDictionary { Source = new Uri(Properties.Resource.Settings) };

                // List<string> strings = new List<string>()
                // {
                //     "200*200 C30 预拌",
                //     "200*200 C35 预拌",
                //     "200*200 C40 预拌",
                //     "200*200 C45 预拌",
                //     "200*200 C50 预拌"
                // };
                // System.Windows.Controls.ComboBox cb = new System.Windows.Controls.ComboBox();
                // cb.ItemsSource = strings;
                // cb.SetValue(System.Windows.Controls.ComboBox.StyleProperty, Resources["x:Null"]);
                // cb.Width = 100;
                // cb.SelectedIndex = 0;
                // cb.HorizontalAlignment = HorizontalAlignment.Center;
                // cb.VerticalAlignment = VerticalAlignment.Center;
                // cb.ToolTip = "选择一个族类型";
                // cb.Visibility = System.Windows.Visibility.Collapsed;

                Button button = new Button
                {
                    //Style = dic["MaterialDesignRaisedButton"] as Style,
                    Width = 90,
                    Content = "载入项目"
                };
                button.Margin = new Thickness(0, 2, 0, 0);
                button.Height = 30;
                //button.Click = Click();
                button.Click += (sender, e) =>
                {
                    loadFamily.FamilyFileName = label.Content.ToString();
                    loadFamily.LoadButtonCont = button.Content.ToString();
                    loadFamily.FamilyFileCategory = FamilyFileCategory;
                    loadFamily.FamilyCategoryName = FamilyCategoryName;
                    loadFamily.FamilyNodeID = FamilyNodeID;
                    loadFamily.FamilyID = FamilyID;
                    loadFamily.FamilyProperties = fpLsList;
                    LoadFamilyEvent.Raise();

                    if (button.Content.ToString() == "放置")
                    {
                        this.WindowState = WindowState.Minimized;
                    }

                    button.Content = "放置";
                    lbi.IsSelected = true;
                    //Refresh();

                    // if (button.Content.ToString() == "放置")
                    // {
                    //     // string _FamilyFileName = label.Content.ToString();
                    //     // string _LoadButtonCont = button.Content.ToString();
                    //     // string _FamilyFileCategory = FamilyFileCategory;
                    //     // string _FamilyCategoryName = FamilyCategoryName;
                    //     // string _FamilyNodeID = FamilyNodeID;
                    //     // LoadFamilyProperty property = new LoadFamilyProperty(loadFamily, LoadFamilyEvent,_FamilyFileName, _LoadButtonCont, _FamilyFileCategory, _FamilyCategoryName, _FamilyNodeID);
                    //     // property.ShowDialog();
                    //
                    //     loadFamily.FamilyFileName = label.Content.ToString();
                    //     loadFamily.LoadButtonCont = button.Content.ToString();
                    //     loadFamily.FamilyFileCategory = FamilyFileCategory;
                    //     loadFamily.FamilyCategoryName = FamilyCategoryName;
                    //     loadFamily.FamilyNodeID = FamilyNodeID;
                    //     LoadFamilyEvent.Raise();
                    //     this.WindowState = WindowState.Minimized;
                    // }

                    // if (button.Content.ToString() == "载入项目")
                    // {
                    //     
                    //     loadFamily.FamilyFileName = label.Content.ToString();
                    //     loadFamily.LoadButtonCont = button.Content.ToString();
                    //     loadFamily.FamilyFileCategory = FamilyFileCategory;
                    //     loadFamily.FamilyCategoryName = FamilyCategoryName;
                    //     loadFamily.FamilyNodeID = FamilyNodeID;
                    //     LoadFamilyEvent.Raise();
                    //
                    //     button.Content = "放置";
                    //     // lable1.Visibility = Visibility.Collapsed;
                    //     // cb.Visibility = Visibility.Visible;
                    //
                    // }
                };
                sp.Children.Add(image);
                sp.Children.Add(label);
                sp.Children.Add(lable1);
                sp.Children.Add(lable2);
                //sp.Children.Add(cb);
                sp.Children.Add(button);
                lbi.Content = sp;
                ListListBoxItem.Add(lbi);
            }
            if (listLength % pagesize == 0)
            {
                tbmaxnum = listLength / pagesize;
            }
            else
            {
                tbmaxnum = listLength / pagesize + 1;
            }
            tbindex.Text = 1.ToString();
            tbmax.Text = tbmaxnum.ToString();
            index = 0;
            tbindexnum = 1;
            return ListListBoxItem.Skip(0).Take(pagesize).ToList();
        }
        // 当前选择项参数字典
        List<FamilyProperty> fpLsList;

        // listbox选项发生变化事件
        private void ListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lb1 = sender as ListBox;
            StackPanel sppp = listBox.Parent as StackPanel;

            ListBoxItem listBoxSelectedItem = lb1.SelectedItem as ListBoxItem;
            if (listBoxSelectedItem != null)
            {
                // 族名称
                string labelstr = String.Empty;
                // 按钮
                string buttonstr = String.Empty;
                // 是否需要设置参数
                string configurable = String.Empty;
                // 参数字典
                List<FamilyParameters> propertys = new List<FamilyParameters>();

                StackPanel spp = listBoxSelectedItem.Content as StackPanel;
                UIElementCollection uiElementCollection = spp.Children;
                foreach (var children in uiElementCollection)
                {
                    if (children is Label)
                    {
                        Label l1 = children as Label;
                        if (l1.Name == "familyName")
                        {
                            labelstr = ((ContentControl)children).Content.ToString();
                        }
                        else if (l1.Name == "configurable")
                        {
                            configurable = ((ContentControl)children).Content.ToString();
                        }
                    }
                    if (children is Button)
                    {
                        buttonstr = ((ContentControl)children).Content.ToString();
                    }
                }
                // 根据动态加载参数名称和参数下拉框
                if (labelstr != "" && configurable == "1")
                {
                    // 当前选择项参数字典 用于放置族时传参
                    fpLsList = new List<FamilyProperty>();

                    sppp.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(229, 240, 215));
                    FamilyPropertySp.Children.Clear();

                    // 遍历数据库中参数列表
                    foreach (var item in familyParameterList)
                    {
                        // 找到当前选中的族的参数名称列表
                        if (item.CategoryName == labelstr)
                        {
                            List<ParametersDictionary> values = parameterDirectionList.Where(r => r.ID == item.ParameterID).ToList();
                            item.ParametersDictionaryList = values;
                            propertys.Add(item);
                            // 用于传参
                            FamilyProperty fp = new FamilyProperty();
                            fp.DispalyPropertyName = item.ParameterName;
                            fp.FamilyPropertyName = item.FamilySymbolParameterName;
                            fp.PropertValue = item.ParametersDictionaryList[0].ParameterValue;
                            fp.ParameterCode = item.ParametersDictionaryList[0].ParameterCode;
                            fpLsList.Add(fp);
                        }
                    }
                    Label title = new Label();
                    title.Content = "族属性 ";
                    title.FontSize = 13;
                    FamilyPropertySp.Children.Add(title);
                    for (int i = 0; i < propertys.Count; i++)
                    {
                        Label lb = new Label();
                        lb.Content = " 丨 " + propertys[i].ParameterName + ":";
                        lb.Margin = new Thickness(10, 0, 0, 0);
                        //lb.FontWeight = FontWeights.Bold;
                        lb.FontSize = 13;
                        FamilyPropertySp.Children.Add(lb);
                        System.Windows.Controls.ComboBox cb = new System.Windows.Controls.ComboBox();
                        cb.ItemsSource = propertys[i].ParametersDictionaryList;
                        //cb.Tag= propertys[i].;
                        cb.DisplayMemberPath = "ParameterValue";
                        cb.SelectedValuePath = "ParameterCode";
                        cb.Name = propertys[i].ParameterName;
                        cb.Margin = new Thickness(5, 0, 0, 0);
                        cb.FontSize = 13;
                        cb.IsEditable = true;
                        cb.SelectionChanged += Cb_SelectionChanged;
                        cb.SelectedIndex = 0;
                        //cb.SetValue(System.Windows.Controls.ComboBox.StyleProperty, Resources["x:Null"]);
                        FamilyPropertySp.Children.Add(cb);

                    }
                }
                else
                {
                    sppp.Background = Brushes.White;
                    if (FamilyPropertySp.Children.Count != 0)
                    {
                        FamilyPropertySp.Children.Clear();
                    }
                }

            }
        }
        // 参数选项切换
        private void Cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 判断是否是初始化
            if (e.RemovedItems.Count > 0)
            {
                System.Windows.Controls.ComboBox cb = sender as System.Windows.Controls.ComboBox;
                string cbName = cb.Name;
                ParametersDictionary selectedItem = (ParametersDictionary)cb.SelectedItem;

                // 修改fpLsList
                for (int i = 0; i < fpLsList.Count; i++)
                {
                    var item = fpLsList[i];
                    if (item.DispalyPropertyName == cbName)
                    {
                        fpLsList.RemoveAt(i);
                        item.PropertValue = selectedItem.ParameterValue;
                        item.ParameterCode = selectedItem.ParameterCode;
                        fpLsList.Insert(i, item);
                        break;
                    }
                }
            }
        }

        private DataSet familyParameterDatas = new DataSet();
        private DataSet DirectionDatas = new DataSet();
        public List<FamilyParameters> familyParameterList { get; set; }
        public List<ParametersDictionary> parameterDirectionList { get; set; }
        // 从数据库获取参数字典
        private void getParameters()
        {
            string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
            string FamilySql = "SELECT [ID],[CategoryName],[ParameterName] ,[ParameterID],[FamilySymbolParameterName] FROM FamilyParameters ORDER BY CategoryName,ID";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataAdapter familyParameter1 = new SqlDataAdapter(FamilySql, conn); //(查询语句和连接工具)
                familyParameter1.Fill(familyParameterDatas); //将适配器数据存入DataSet工具中
                familyParameterList = new List<FamilyParameters>();
                FamilyParameters familyParameters;
                foreach (DataRow row in familyParameterDatas.Tables[0].Rows)
                {
                    familyParameters = new FamilyParameters();
                    familyParameters.ID = DataProcessor.ToValue(row, "ID", 0);
                    familyParameters.CategoryName = DataProcessor.ToValue(row, "CategoryName", "");
                    familyParameters.ParameterName = DataProcessor.ToValue(row, "ParameterName", "");
                    familyParameters.ParameterID = DataProcessor.ToValue(row, "ParameterID", "");
                    familyParameters.FamilySymbolParameterName = DataProcessor.ToValue(row, "FamilySymbolParameterName", "");

                    familyParameterList.Add(familyParameters);
                }

            }

            FamilySql = "SELECT [ID],[ParameterValue],[ParameterCode] FROM ParametersDictionary ";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataAdapter familyParameter1 = new SqlDataAdapter(FamilySql, conn); //(查询语句和连接工具)
                familyParameter1.Fill(DirectionDatas); //将适配器数据存入DataSet工具中
                parameterDirectionList = new List<ParametersDictionary>();
                ParametersDictionary parameterDirection;
                foreach (DataRow row in DirectionDatas.Tables[0].Rows)
                {
                    parameterDirection = new ParametersDictionary();
                    parameterDirection.ID = DataProcessor.ToValue(row, "ID", "");
                    parameterDirection.ParameterValue = DataProcessor.ToValue(row, "ParameterValue", "");
                    parameterDirection.ParameterCode = DataProcessor.ToValue(row, "ParameterCode", "");
                    parameterDirectionList.Add(parameterDirection);
                }
            }
        }

        #region 查询数据
        DataSet FamilyDatas = new DataSet();
        DataSet TreeNodeDatas = new DataSet();
        DataSet CategoryDatas = new DataSet();
        private List<TreeNode> TreeNodes;
        private List<Category> Categorys;
        //查询FamilyData
        private ObservableCollection<FamilyFile> FamilyData()
        {
            string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
            string FamilySql = "SELECT [FamilyName],[FamilyCategoryName],[author] ,[FamilyFileCategory],[FamilyNodeID],[ProjectFeatures],[Configurable],[FamilyID] FROM Family where IsEnable = 1";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataAdapter FamilyData = new SqlDataAdapter(FamilySql, conn);   //(查询语句和连接工具)
                FamilyData.Fill(FamilyDatas);    //将适配器数据存入DataSet工具中
                FamilyFiles = new ObservableCollection<FamilyFile>();
                FamilyFile FamilyFile = null;
                foreach (DataRow row in FamilyDatas.Tables[0].Rows)
                {
                    FamilyFile = new FamilyFile();
                    FamilyFile.ImagePath = DataProcessor.ToValue(row, "FamilyName", "0");
                    FamilyFile.FamilyName = DataProcessor.ToValue(row, "FamilyName", "0");
                    FamilyFile.FamilyCategoryName = DataProcessor.ToValue(row, "FamilyCategoryName", "0");
                    FamilyFile.FamilyFileCategory = DataProcessor.ToValue(row, "FamilyFileCategory", "1");
                    FamilyFile.author = DataProcessor.ToValue(row, "author", "1");
                    FamilyFile.FamilyNodeID = DataProcessor.ToValue(row, "FamilyNodeID", "0");
                    FamilyFile.ProjectFeatures = DataProcessor.ToValue(row, "ProjectFeatures", "0");
                    FamilyFile.Configurable = DataProcessor.ToValue(row, "Configurable", 0);
                    FamilyFile.FamilyID = DataProcessor.ToValue(row, "FamilyID", "0");
                    FamilyFiles.Add(FamilyFile);
                }
                return FamilyFiles;
            }
        }

        //查询TreeNodeData
        private List<TreeNode> TreeNodeData()
        {
            string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
            string TreeNodeSql = "SELECT * FROM TreeNode";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataAdapter TreeNodeData = new SqlDataAdapter(TreeNodeSql, conn);   //(查询语句和连接工具)
                TreeNodeData.Fill(TreeNodeDatas);    //将适配器数据存入DataSet工具中
                TreeNodes = new List<TreeNode>();
                TreeNode treenode = null;
                string path = Set.getaddress();
                path = path.Substring(0, path.Length);
                foreach (DataRow row in TreeNodeDatas.Tables[0].Rows)
                {
                    treenode = new TreeNode
                    {
                        NodeID = DataProcessor.ToValue(row, "NodeID", 0),
                        ParentID = DataProcessor.ToValue(row, "ParentID", 0),
                        NodeName = DataProcessor.ToValue(row, "NodeName", "0"),
                        NodeCategory = DataProcessor.ToValue(row, "NodeCategory", "0"),
                        IsLowestLevel = DataProcessor.ToValue(row, "IsLowestLevel", 0),
                    };
                    if (DataProcessor.ToValue(row, "LevelNo", "1") == "1")
                    {
                        string firstpath = System.IO.Path.Combine(path, "image\\文件.png");
                        treenode.NodesImage = firstpath;
                    }
                    else
                    {
                        string sectpath = System.IO.Path.Combine(path, "image\\文件夹_o.png");
                        treenode.NodesImage = sectpath;
                    }
                    TreeNodes.Add(treenode);
                }
                // 缓存
                //CacheManagerHelper.Set<List<TreeNode>>("TreeNodes", TreeNodes);
                return TreeNodes;
            }
        }

        //查询CategoryData
        private List<MainViewModel.Category> CategoryData()
        {
            string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
            string TreeNodeSql = "SELECT * FROM Category";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataAdapter CategoryData = new SqlDataAdapter(TreeNodeSql, conn);   //(查询语句和连接工具)
                CategoryData.Fill(CategoryDatas);    //将适配器数据存入DataSet工具中
                Categorys = new List<Category>();
                Category category = null;
                foreach (DataRow row in CategoryDatas.Tables[0].Rows)
                {
                    category = new Category
                    {
                        CategoryName = DataProcessor.ToValue(row, "CategoryName", "0"),

                    };
                    Categorys.Add(category);
                }
                // 缓存
                //CacheManagerHelper.Set<List<MainViewModel.Category>>("Categorys", Categorys);
                return Categorys;
            }
        }
        #endregion

        //菜单按钮
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock tempBtn = (TextBlock)sender;

            chapterTree.ItemsSource = GetNodes(0, TreeNodes, tempBtn.Text);
        }

        //搜索框按钮
        private void selButton_Click(object sender, RoutedEventArgs e)
        {
            //if (e.Method. == Key.Enter)
            //{
            //MessageBox.Show(SelectText.Text);
            string selecttext = "";
            if (SelectText.Text != "")
            {
                selecttext = SelectText.Text;
            };

            listBox.ItemsSource = ListBoxFamily(pagesize, "", selecttext);
            SelectText.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            //}                 

        }


        #region  树结构展开收缩

        //树形节点按钮
        private void Label_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Label tempBtn = (Label)sender;
            //MessageBox.Show(tempBtn.Content.ToString());
            int result = Int32.Parse(tempBtn.Tag.ToString().Split(',')[1]);
            if (result.Equals(1))
            {
                listBox.ItemsSource = ListBoxFamily(pagesize, tempBtn.Tag.ToString().Split(',')[0].ToString(), "");
            }

        }
        // 全部收缩
        private void btnCollapseAll(object sender, RoutedEventArgs e)
        {
            foreach (var item in chapterTree.Items)
            {
                DependencyObject dObject = chapterTree.ItemContainerGenerator.ContainerFromItem(item);
                CollapseTreeviewItems(((TreeViewItem)dObject));
            }

        }

        // 全部展开
        private void btnExpandAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in chapterTree.Items)
            {
                DependencyObject dObject = chapterTree.ItemContainerGenerator.ContainerFromItem(item);
                ((TreeViewItem)dObject).ExpandSubtree();
            }
        }
        private void CollapseTreeviewItems(TreeViewItem Item)
        {
            Item.IsExpanded = false;

            foreach (var item in Item.Items)
            {
                DependencyObject dObject = chapterTree.ItemContainerGenerator.ContainerFromItem(item);

                if (dObject != null)
                {
                    ((TreeViewItem)dObject).IsExpanded = false;

                    if (((TreeViewItem)dObject).HasItems)
                    {
                        CollapseTreeviewItems(((TreeViewItem)dObject));
                    }
                }
            }
        }
        #endregion

    }
}
